<template>
    <div>
        <el-dialog title="告警处理" :visible.sync="dialogVisible" width="500px" :before-close="closeAddDialog"
            :close-on-click-modal="false" append-to-body>
            <el-form :model="ruleForm" :rules="rules" ref="refalarmHandleInfo" label-width="110px">
                <el-form-item size="small" label="告警类型" prop="alarmFactor">
                    <el-autocomplete clearable @clear="clearAlarmFactor" v-model="ruleForm.alarmFactor"
                        :fetch-suggestions="querySearch" placeholder="请选择告警类型" @select="handleSelect"
                        style="width: 330px" :maxlength="10"></el-autocomplete>
                </el-form-item>

                <el-form-item size="small" label="照片">
                    <el-upload :class="{ disabled: uploadDisabled }" :on-remove="handleRemove"
                        :on-change="uploadSectionFile" :action="baseUrl" list-type="picture-card" accept=".jpg,.png"
                        :on-preview="handlePictureCardPreview" :headers="headers" :before-upload="beforeAvatarUpload"
                        :on-success="handleSuccessFunction" :limit="1" :on-exceed="handleExceedScene"
                        :file-list="fileList">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                </el-form-item>

                <el-form-item size="small" label="反馈内容">
                    <el-input maxlength="30" rows="3" type="textarea" v-model="ruleForm.feedback" resize="none"
                        :autosize="{ minRows: 2, maxRows: 5 }"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="closeAddDialog" class="cancel-button">取 消</el-button>
                <el-button size="small" @click="addSubmit" class="confirm-button">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog :visible.sync="dialogVisible2" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
    </div>
</template>

<script>
import {
    reqAlarmHandle,
    reqClosedLoop,
    reqAlarmbatchHandling,
    reqBatchClosedLoop,
} from "@/api/api";
import { mapState } from "vuex";
import asc from "@utils/asc.js"; //加密解密

export default {
    props: ["alarmid"],
    data() {
        return {
            fileList: [],
            headers: {
                token: asc.decrypt(sessionStorage.getItem("token")),
            },
            dialogVisible2: false,
            dialogImageUrl: "",
            ruleForm: {
                alarmFactor: "",
                feedback: "",
                pic: "",
                userId: "",
            },
            dialogVisible: false,
            // 表单验证规则
            rules: {
                alarmFactor: [
                    {
                        required: true,
                        message: "请选择告警类型",
                        trigger: ["blur", "change"],
                    },
                ],
            },
            alarmFactorList: [
                {
                    id: 0,
                    name: "火警",
                },
                {
                    id: 1,
                    name: "误报",
                },
                {
                    id: 2,
                    name: "测试",
                },
                {
                    id: 3,
                    name: "其他",
                },
            ],
            restaurants: [],
            uploadDisabled: false, //加号默认显示
        };
    },
    computed: {
        ...mapState(["user"]),
    },
    watch: {
        // alarmHandleInfo: {
        //   handler(val) {
        //     // console.log(val);
        //     // this.AlarmHandleResult()
        //   },
        // },
        dialogVisible(e) {
            if (e) {
                this.uploadDisabled = false;
            }
        },
    },
    methods: {
        uploadSectionFile(file, fileList) {
            if (fileList.length >= 1) {
                this.uploadDisabled = true; //隐藏加号
            }
        },
        //删除照片
        handleRemove(file) {
            this.ruleForm.pic = "";
            setTimeout(() => {
                this.uploadDisabled = false;
            }, 1000);
        },
        querySearch(queryString, cb) {
            var restaurants = this.restaurants;
            var results = queryString
                ? restaurants.filter(this.createFilter(queryString))
                : restaurants;
            // 调用 callback 返回建议列表的数据
            cb(results);
        },
        createFilter(queryString) {
            return (restaurant) => {
                return (
                    restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
                    0
                );
            };
        },
        loadAll() {
            return [
                { value: "火警" },
                { value: "误报" },
                { value: "测试" },
                { value: "其它" },
            ];
        },
        handleSelect(item) {
            // console.log(item);
        },
        // 清除告警因素
        clearAlarmFactor() {
            this.restaurants = this.loadAll();
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible2 = true;
        },
        // 上传文件之前的钩子
        beforeAvatarUpload(file) {
            let isJPG = true;
            let isLt = file.size / 1024 < 20000; // 判断是否小于500Kb
            if (file.type !== "image/png" && file.type !== "image/jpeg") {
                this.uploadDisabled = false;
                this.$modal.notifyWarning("图片只能是 jpg/png 格式!");
                isJPG = false;
                return isJPG;
            } else if (!isLt) {
                this.$modal.notifyWarning("图片大小不能超过20MB! 请重新上传");
                this.uploadDisabled = false;
                isJPG = false;
            }
            return isJPG;
        },
        // 上传成功
        handleSuccessFunction(response, file, fileList) {
            this.ruleForm.pic = file.response.data.url;
        },
        // 文件超出个数限制时的钩子
        handleExceedScene() {
            this.$modal.notifyWarning(`照片只能上传一张`);
        },
        addSubmit() {
            this.$refs.refalarmHandleInfo.validate(async (valid) => {
                if (!valid) return;
                const res = await reqAlarmHandle({
                    id: this.alarmid,
                    alarmFactor: this.ruleForm.alarmFactor,
                    feedback: this.ruleForm.feedback,
                    pic: this.ruleForm.pic,
                    userId: this.user.userId,
                });
                if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
                // 完结
                let res2 = await reqClosedLoop({
                    id: this.alarmid,
                });
                if (res2.code !== 20000)
                    return this.$modal.notifyWarning(res2.message);
                this.$modal.notifySuccess("处理成功");
                this.$parent.AlarmList(); //更新告警列表
                this.closeAddDialog();
            });
        },
        // 点击关闭弹框
        closeAddDialog() {
            this.dialogVisible = false;
            this.fileList = [];
            (this.ruleForm = {
                alarmFactor: "",
                feedback: "",
                pic: "",
                userId: "",
            }),
                this.$refs.refalarmHandleInfo.resetFields();
            // this.uploadDisabled = false;
        },
    },
    mounted() {
        this.restaurants = this.loadAll();
    },
    created() {
        this.baseUrl = `${this.$baseURL_copy}file/upload`;
    },
    deactivated() {
        if (this.$refs.refalarmHandleInfo != null) {
            this.closeAddDialog();
        }
        this.dialogVisible2 = false;
    },
};
</script>

<style lang="less" scoped>
@import url("../../../views/common.less");

::v-deep .el-dialog__body {
    // min-height: 120px !important;
    min-height: 50px !important;
}

/deep/ .el-textarea__inner {
    resize: none;
}

// 隐藏加号
/deep/ .disabled .el-upload--picture-card {
    display: none !important;
}
</style>